package com.wteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wteam.PoJo.DTO.coupon;
import com.wteam.PoJo.DTO.coupon_member;
import com.wteam.PoJo.DTO.memberdto;
import com.wteam.PoJo.VO.couponVo;
import com.wteam.config.JWT.jwt;
import com.wteam.mapper.CouponMenmbermapper;
import com.wteam.mapper.Couponmapper;
import com.wteam.mapper.Memberdtomapper;
import com.wteam.mapper.Membermapper;
import com.wteam.service.CouponService;
import com.wteam.untils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j

@Service
public class Couponserviceimpl implements CouponService {
    @Autowired
    private Memberdtomapper memberdto;
    @Autowired
    private Couponmapper couponmapper;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private Membermapper membermapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CouponMenmbermapper couponMenmbermapper;

    @Override
    public Result save(couponVo coupon) {
        com.wteam.PoJo.DTO.coupon c = new coupon();

        BeanUtils.copyProperties(coupon, c);

        int insert = couponmapper.insert(c);

        return Result.success();
    }

    @Override
    public Result listConpon(Integer page, Integer pagesize) {

        String key = "couponlist_";
        //查看redis有没有缓存有直接返回
        List<coupon> RedisRecords = redisTemplate.opsForHash().values(key);
        //没有缓存
        if (RedisRecords.size() == 0) {

            IPage<coupon> iPage = new Page<>(page, pagesize);
            LambdaQueryWrapper<coupon> qw = new LambdaQueryWrapper();
            qw.ge(coupon::getEndTime, LocalDateTime.now())
                    .le(coupon::getStartTime, LocalDateTime.now());
            IPage<coupon> iPage1 = couponmapper.selectPage(iPage, qw);
            List<coupon> records = iPage1.getRecords();

            //查看我的优惠卷
            LambdaQueryWrapper<coupon_member> queryWrappe = new LambdaQueryWrapper();

            Map<String, Object> claims = jwt.parseJWT(httpServletRequest.getHeader("token"));
            Integer memberId = (Integer) claims.get("id");
            queryWrappe.eq(coupon_member::getMemberId, memberId);
            List<coupon_member> coupon_members = couponMenmbermapper.selectList(queryWrappe);

            for (coupon record : records) {
                log.info(records.toString());
                for (coupon_member coupon_member : coupon_members) {
                    log.info(coupon_member.toString());
                    if (record.getId() == coupon_member.getCouponId()) {
                        record.setMemberstatus(2);
                    }

                }

            }
            //缓存records
            for (coupon record : records) {
                redisTemplate.opsForHash().put(key, record.getId() + page + "_" + pagesize + "_", record);

            }
            return Result.success(records);

        }
        //有缓存，但是要看缓存时间，过期的删除
        for (coupon record : RedisRecords) {
            Boolean A = record.getEndTime().isAfter(LocalDateTime.now());
            if (!A) {
                RedisRecords.remove(record);
                redisTemplate.opsForHash().delete(key, record.getId() + page + "_" + pagesize + "_");
            }
        }
        return Result.success(RedisRecords);


//            // 存储coupon对象到Sorted Set
//            for (coupon coupon : records) {
//                String couponId = generateUniqueCouponId(); // 生成唯一标识符
//                long expirationTime = coupon.getExpirationTime().toEpochSecond(); // 过期时间转换为Unix时间戳
//                redisTemplate.opsForZSet().add("coupons", couponId, expirationTime);
//                redisTemplate.opsForValue().set("coupon:" + couponId, coupon);
//            }
//
//// 定期检查过期时间并清理过期对象
//            long currentTimestamp = Instant.now().getEpochSecond();
//            Set<Object> expiredCoupons = redisTemplate.opsForZSet().rangeByScore("coupons", 0, currentTimestamp);
//            for (Object couponId : expiredCoupons) {
//                redisTemplate.delete("coupon:" + couponId); // 删除过期coupon对象
//                redisTemplate.opsForZSet().remove("coupons", couponId); // 从Sorted Set中移除过期对象
//            }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)

    public Result UserGetCopon(Integer conponId) {
        //先删缓存
        redisTemplate.delete("couponlist_");

        //2判断被领数量和发行数量
        LambdaQueryWrapper<coupon> PUBLIC_RECEIVE = new LambdaQueryWrapper();
        PUBLIC_RECEIVE.eq(coupon::getId, conponId);
        coupon coupon = couponmapper.selectOne(PUBLIC_RECEIVE);
        if (coupon.getPublishNum() <= coupon.getReceivedNum()) {
            return Result.error("优惠卷已被领完");
        }


//        //1.判断优惠卷是否已领
        Map<String, Object> claims = jwt.parseJWT(httpServletRequest.getHeader("token"));
        Integer memberId = (Integer) claims.get("id");
        LambdaQueryWrapper<coupon_member> conponIdAndMemberId = new LambdaQueryWrapper();
        conponIdAndMemberId.eq(coupon_member::getMemberId, memberId)
                .eq(coupon_member::getCouponId, conponId);
        Long aLong = couponMenmbermapper.selectCount(conponIdAndMemberId);
        if (aLong != 0) {
            return Result.error("你已领取该优惠卷");
        }

        //3.1 查看我的积分有多少
        Integer MemberPoint = membermapper.selectpointbyId(memberId);
        log.info(MemberPoint.toString());
        //3.2 查看所需积分
        Integer CouponPoint = couponmapper.selectpoint(conponId);
        //查看积分是不是很多
        if (MemberPoint < CouponPoint) {
            return Result.error("积分不足");
        }

        log.info(CouponPoint.toString());
        //领取并更新我的积分
        Integer updateMemberpoint = MemberPoint - CouponPoint;
        log.info(updateMemberpoint.toString());
        memberdto m = new memberdto();
        m.setId(memberId);
        m.setPoint(updateMemberpoint);
        log.info(m.toString() + "sdfvsdvfcsd");
        memberdto.updateById(m);

        //更新coupon库里的领取数量
        com.wteam.PoJo.DTO.coupon coupon1 = couponmapper.selectById(conponId);
        coupon1.setReceivedNum(coupon1.getReceivedNum() + 1);
        couponmapper.updateById(coupon1);

        //插入coupon_member信息
        coupon_member couponMember = new coupon_member();
        couponMember.setCouponId(conponId);
        couponMember.setMemberId(memberId);
        couponMenmbermapper.insert(couponMember);

        return Result.success();
    }

}
